//
//  MSSearchViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/9.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSSearchViewController.h"
#import "MSProjectDetailViewController.h"

@interface MSSearchViewController ()<UITextFieldDelegate,UIScrollViewDelegate>
@property(nonatomic,strong)MSSearchBar    *searchBar;
@property (nonatomic, copy)NSString       *projectFile;
@property (nonatomic, copy)NSString       *tradeFile;
@property(nonatomic,strong)NSFileManager  *fileManager;
@property(nonatomic,strong)NSMutableArray *searchArray;
@property(nonatomic,strong)NSMutableArray *historyRecordArray;
@property(nonatomic,strong)MSSearchTableViewController *searchResultList;
@end

@implementation MSSearchViewController

- (void)initNavigationBar{
    [super initNavigationBar];
    leftBarBtn.hidden = YES;
    rightBarBtn.hidden = NO;
    rightBarBtn.frame = CGRectMake(APPFRAME.size.width-55, 24, 40, 40);
    rightBarBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightBarBtn setTitle:@"取消" forState:UIControlStateNormal];
    [rightBarBtn setTitleColor:kLightBlackColor forState:UIControlStateNormal];
    [rightBarBtn addTarget:self action:@selector(rightBarBtnAction) forControlEvents:UIControlEventTouchUpInside];
    _navBarView.backgroundColor = kDefaultViewBackgroundColor;
    
    NSString *placeHoder = @"";
    if (self.searchType == MSSearchType_Project) {
        placeHoder = @"请输入项目名查找项目";
    }
    if (self.searchType == MSSearchType_Trade) {
        placeHoder = @"请输入项目名称或联系人搜索交易";
    }
    
    self.searchBar = [[MSSearchBar alloc] initWithFrame:CGRectMake(5, 20, SCREENWIDTH-57, 40)];
    self.searchBar.placeholder = placeHoder;
    self.searchBar.cornerRadius = 2;
    self.searchBar.delegate = (id)self;
    self.searchBar.placeholderColor = kDarkGrayColor;
    self.searchBar.borderColor = kNormalGray;
//    self.searchBar.backgroundColor = [UIColor whiteColor];
    self.searchBar.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
    [_navBarView addSubview:self.searchBar];
    [self performBlock:^{
        [self.searchBar becomeFirstResponder];
    } afterDelay:0.3];
}

- (void)rightBarBtnAction{
    [rootNavigation popViewControllerAnimated:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    [self.searchBar resignFirstResponder];
}

-(void)initUI
{
    self.contentView.backgroundColor = kDefaultViewBackgroundColor;
    //搜索结果列表
    self.searchResultList = [[MSSearchTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    self.searchResultList.view.frame = self.contentView.bounds;
    self.searchResultList.enableRefresh = NO;
    self.searchResultList.enableRequest = YES;
    self.searchResultList.delegate = (id)self;
    self.searchResultList.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.searchResultList.view];
    
    NSString*documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    self.projectFile = [documentsPath stringByAppendingPathComponent:@"ProjectFile.plist"];
    self.tradeFile = [documentsPath stringByAppendingPathComponent:@"TradeFile.plist"];
    
    self.fileManager = [NSFileManager defaultManager];
    self.searchResultList.searchType = MSSearchType_History;
    
    if (self.searchType == MSSearchType_Project) {//项目
        if ([self.fileManager fileExistsAtPath:self.projectFile]) {
            self.searchResultList.dataArray = [[NSMutableArray alloc] initWithContentsOfFile:self.projectFile];
            self.historyRecordArray = self.searchResultList.dataArray;
        }
        else{//无项目搜索记录
            self.historyRecordArray = [NSMutableArray arrayWithCapacity:0];
        }
    }
    else{//交易
        if ([self.fileManager fileExistsAtPath:self.tradeFile]) {
            self.searchResultList.dataArray = [[NSMutableArray alloc] initWithContentsOfFile:self.tradeFile];
            self.historyRecordArray = self.searchResultList.dataArray;
        }
        else{//无交易搜索记录
            self.historyRecordArray = [NSMutableArray arrayWithCapacity:0];
        }
    }
}

- (void)testDataFunc{
    MSProjectModel *model = [[MSProjectModel alloc] init];
    model.title = @"上海浦东世和空港中心商业住房项目";
    model.projectType =  @"房地产";
    model.projectState =  @"主体施工";
    model.investment =  @"2亿";
    model.address =  @"上海";
    model.time =  @"2016.10.08";
    model.introduction =  @"项目为四栋单独塔楼，一座宾馆，一做酒店式办公楼，地下部分主题为一个小楼盘，整个项目投资回报率较高";
    
    MSProjectModel *model1 = [[MSProjectModel alloc] init];
    model1.title = @"苏州永华置业有限公司 意境鸣镝西部仓库";
    model1.projectType =  @"酒店";
    model1.projectState =  @"主体施工";
    model1.investment =  @"3亿";
    model1.address =  @"苏州";
    model1.time =  @"2016.10.08";
    model1.introduction =  @"项目为四栋单独塔楼，一座宾馆。";
    
    MSProjectModel *model2 = [[MSProjectModel alloc] init];
    model2.title = @"中国光大国际有限公司深圳办事处";
    model2.projectType =  @"市政公用";
    model2.projectState =  @"主体施工";
    model2.investment =  @"6亿";
    model2.address =  @"成都";
    model2.time =  @"2016.9.15";
    model2.introduction =  @"项目为四栋单独塔楼，一座宾馆，一做酒店式办公楼，地下部分主题为一个小楼盘，整个项目投资回报率较高";
    
    MSTradeModel *model5 = [[MSTradeModel alloc] init];
    model5.title = @"上海浦东世和空港中心商业住房项目";
    model5.projectType = @"类型   求购业主联系人信息";
    model5.tradeState = @"交易中";
    model5.tradeNum = @"3次交易";
    model5.name = @"姓名   周世鹏";
    model5.position = @"经理";
    model5.theme = @"项目主题    电缆附件招标最新进展";
    model5.content = @"内容   杭州地铁二号线目前极影施工阶段";
    model5.tradeEvaluate = @"评价              ";
    model5.tradePrice = @"12";
    model5.memberType = @"[匿名会员]";
    model5.memberLevel = @"2钻会员";
    model5.time = @"2016.9.15";

    if (self.searchType == MSSearchType_Project) {//项目
        self.searchArray = [@[model,model1,model2,model,model2,model1,model] mutableCopy];
    }
    else{//交易
        self.searchArray = [@[model5,model5,model5,model5,model5,model5] mutableCopy];
    }
}

#pragma mark - getData
- (void)updateViewController:(NSNotification *)note
{
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"ProjectSearchRelevance"]!=nil){
            if (responseDic[@"state"]!=nil){
                self.searchResultList.totalPagesNum = [responseDic[@"totalPage"] intValue];
                if (self.searchResultList.pageNum == 1) {
                    self.searchResultList.dataArray = nil;
                }
                NSMutableArray *dataArrray = [[NSMutableArray alloc] initWithArray:self.searchResultList.dataArray];
                [dataArrray addObjectsFromArray:responseDic[@"ProjectSearchRelevance"]];
                self.searchResultList.dataArray = dataArrray;
            }
            else{
//                self.searchResultList.dataArray = self.searchResultList.dataArray;
            }
        }
        if (responseDic[@"TradeSearchRelevance"]!=nil){
            if (responseDic[@"state"]!=nil){
                self.searchResultList.totalPagesNum = [responseDic[@"totalPage"] intValue];
                if (self.searchResultList.pageNum == 1) {
                    self.searchResultList.dataArray = nil;
                }
                NSMutableArray *dataArrray = [[NSMutableArray alloc] initWithArray:self.searchResultList.dataArray];
                [dataArrray addObjectsFromArray:responseDic[@"TradeSearchRelevance"]];
                self.searchResultList.dataArray = dataArrray;
            }
            else{
                self.searchResultList.dataArray = self.searchResultList.dataArray;
            }
        }
    }
}

#pragma mark - tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchResultList.searchType == MSSearchType_History)
    {//历史记录列表
        self.searchBar.text = self.historyRecordArray[indexPath.row];
        //        [self searchBar:self.searchBar textDidChange:self.searchResultList.dataArray[indexPath.row]];
        [self searchBarSearchButtonClicked:self.searchBar];
    }
    else
    {//匹配结果列表，跳转
        if (self.searchType == MSSearchType_Project) {
            MSProjectModel *model = self.searchResultList.dataArray[indexPath.row];
            MSProjectDetailViewController *vc = [[MSProjectDetailViewController alloc] init];
            vc.projectId = model.itemID;
            [rootNavigation pushViewController:vc animated:YES];
        }
        if (self.searchType == MSSearchType_Trade){
            MSTradeModel *model = self.searchResultList.dataArray[indexPath.row];
            if (model.isSelf) {
                [HDUtil showMessage:@"自己不能交易自己发布的交易"];
                return;
            }
            MyTradeConfirmViewController *vc = [[MyTradeConfirmViewController alloc] init];
            vc.model = model;
            [rootNavigation pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//    self.searchResultList.enableRefresh = NO;
    self.searchResultList.enableRequest = NO;
    if ([[searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0 || searchText.length<2) {//字符全是空格，不做操作
        if (self.searchType == MSSearchType_Project) {//项目
            if ([self.fileManager fileExistsAtPath:self.projectFile]) {
                self.searchResultList.searchType = MSSearchType_History;
                self.searchResultList.dataArray = [[NSMutableArray alloc] initWithContentsOfFile:self.projectFile];
            }
            else{//无项目搜索记录
                self.searchResultList.dataArray = nil;
            }
        }
        else{//交易
            if ([self.fileManager fileExistsAtPath:self.tradeFile]) {
                self.searchResultList.searchType = MSSearchType_History;
                self.searchResultList.dataArray = [[NSMutableArray alloc] initWithContentsOfFile:self.tradeFile];
            }
            else{//无交易搜索记录
                self.searchResultList.dataArray = nil;
            }
        }
    }
    else{//无空字符时，开始匹配数据
        if (searchText.length >1) {
            self.searchResultList.pageNum = 1;
            if (self.searchType == MSSearchType_Project)
            {//
                self.searchResultList.searchType = MSSearchType_Project;
                [self requestSearchResult:NO];
            }
            else{//
                self.searchResultList.searchType = MSSearchType_Trade;
                [self requestSearchResult:NO];
            }
        }
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    if ([[searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0 && searchBar.text.length<2) {
        
    }
    else{
        //        NSLog(@"点击了搜索无空格 ======%@",self.searchFile);
//        self.searchResultList.enableRefresh = YES;
        self.searchResultList.enableRequest = YES;
        
        if (![self.historyRecordArray containsObject:searchBar.text]) {
            [self.historyRecordArray insertObject:searchBar.text atIndex:0];
        }
        self.searchResultList.pageNum = 1;
        [self requestSearchResult:NO];
        if (self.searchType == MSSearchType_Project) {//项目
            [self.historyRecordArray writeToFile:self.projectFile atomically:YES];
        }
        else{//交易
            [self.historyRecordArray writeToFile:self.tradeFile atomically:YES];
        }
    }
}

#pragma mark - clearHistoryrecord
- (void)clearClick:(GXButton*)clickBtn{
    if (self.searchType == MSSearchType_Project) {//项目
        [self.fileManager removeItemAtPath:self.projectFile error:nil];
    }
    else if (self.searchType == MSSearchType_Trade){//交易
        [self.fileManager removeItemAtPath:self.tradeFile error:nil];
    }
    self.historyRecordArray = [NSMutableArray arrayWithCapacity:0];
    self.searchResultList.searchType = MSSearchType_History;
    self.searchResultList.dataArray = nil;
}

- (void)deleteCurrentHistoty:(NSInteger)rowIndex{
    [self.historyRecordArray removeObjectAtIndex:rowIndex];
    
    self.searchResultList.dataArray = self.historyRecordArray;
//    [self.searchResultList.tableView reloadData];
    if (self.searchType == MSSearchType_Project) {//项目
        [self.historyRecordArray writeToFile:self.projectFile atomically:YES];
    }
    else{//交易
        [self.historyRecordArray writeToFile:self.tradeFile atomically:YES];
    }
}
#pragma mark DYTableViewProtocol
/** 上拉 */
- (void)pullTableView:(UITableView *)tableView isNextPage:(BOOL)isNextPage{
    self.searchResultList.pageNum++;
    [self requestSearchResult:YES];
}

- (void)requestSearchResult:(BOOL)isPull{
    UIView *hudView = isPull?nil:self.contentView;
    NSString *pageNumber = [NSString stringWithFormat:@"%d",self.searchResultList.pageNum];
    if (self.searchType == MSSearchType_Project) {//
//        NSDictionary *dict = @{@"pageNo":pageNumber,@"pageSize":@"15"};
        self.searchResultList.searchType = MSSearchType_Project;
//        self.searchResultList.dataArray = self.searchArray;
        NSDictionary *dict = @{@"provinces":@"",
                               @"citys":@"",
                               @"industrys":@"",
                               @"stages":@"",
                               @"investment":@"",
                               @"onlineTime":@"",
                               @"kw":self.searchBar.text,
                               @"pageNo":pageNumber,
                               @"pageSize":@"15",
                               };
        [netEngine requestProjectSearchRelevanceWithTarget:self.VctrID hudView:hudView keyword:@"" params:dict];
    }
    else if (self.searchType == MSSearchType_Trade){//交易
        NSDictionary *dict = @{@"province":@"",
                               @"city":@"",
                               @"industry":@"",
                               @"status":@"",
                               @"type":@"",
                               @"onlineTime":@"",
                               @"kw":self.searchBar.text,
                               @"pageNo":pageNumber,
                               @"pageSize":@"15",
                               };

        self.searchResultList.searchType = MSSearchType_Trade;
//        self.searchResultList.dataArray = self.searchArray;
        
        [netEngine requestTradeSearchRelevanceWithTarget:self.VctrID hudView:hudView keyword:self.searchBar.text params:dict];
    }
    
}

#pragma mark - scrollviewBeginDragging
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.searchBar resignFirstResponder];
}

@end
